<!--
+----------------------------------------------------------------------
| 友得云客  - 开启房产营销新纪元
+----------------------------------------------------------------------
| Copyright (c) 2019~2023 优得（西安）信息科技有限公司版权所有
+----------------------------------------------------------------------
| Licensed 友得云客不是自由软件 未经允许不可移除相关版权
+----------------------------------------------------------------------
| Author: www.youdeyunke.com
+----------------------------------------------------------------------
-->
<template>
    <div class="app-container" v-loading="loading">
        <el-card>
            <div class="myheader">
                <div class="part-left">
                    <div class="block">
                        <el-input v-model="kw" round style="border-radius: 100%; width: 250px" size="small"
                            placeholder="搜索小区">
                            <el-button slot="append" icon="el-icon-search" @click="doSearch" />
                        </el-input>
                        <el-button v-if="kw" type="text" size="small" @click="clearKw">清空</el-button>
                    </div>

                    <div class="block">
                        城市：
                        <city-selector custom-style="width:120px;" v-model="cityId" />
                    </div>
                </div>
                <div class="part-right">
                    <div class="block">
                        <el-button :disabled="loading" icon="el-icon-refresh" size="small" type="default" plain round
                            @click="loadData">刷新数据</el-button>
                    </div>

                    <div class="block">
                        <el-button size="small" type="primary" round icon="el-icon-plus"
                            @click="newFormHandle">新建小区</el-button>
                    </div>
                </div>
            </div>
            <el-table :data="items" highlight-current-row @row-click="itemSelect">
                <el-table-column label="城市">
                    <template slot-scope="scope">
                        <span v-if="scope.row.district">{{ scope.row.district.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="名称" />
                <el-table-column prop="street" label="地址" />
                <el-table-column label="操作" :width="140">
                    <template slot-scope="scope">
                        <el-link type="primary" @click="editHandle(scope.row)">编辑</el-link>
                        <el-link type="danger" @click="deleteHandle(scope.row.id)">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pager">
                <el-pagination hide-on-single-page background layout="total, sizes, prev, pager, next, jumper" :total="total"
                    :page-sizes="[10, 20, 50, 100]" :page-size="per_page" @current-change="updateCurrentPage"
                    @size-change="updatePageSize" />
            </div>
        </el-card>

        <el-dialog :visible.sync="showForm" :fullscreen="false" :destroy-on-close="true" width="600px" v-loading="loading"
            title="资料管理">
            <el-form label-position="right" label-width="120px" size="mini" style="width: 600px">
                <el-form-item label="区域" required>
                    <city-district-selector custom-style="width: 200px" size="mini" v-model="currentItem.district_id" />
                </el-form-item>

                <el-form-item label="名称" required>
                    <poi-search custom-style="width:200px;" :city-id="currentItem.city_id" @change="poiSelectHandle"
                        size="mini" v-model="currentItem.name" />
                </el-form-item>

                <el-form-item label="地址" required>
                    <el-input style="width: 400px" v-model="currentItem.street"></el-input>
                </el-form-item>

                <el-form-item label="地图定位" required>
                    <map-marker width="400" height="300" :lat="currentItem.latitude" :lng="currentItem.longitude"
                        @change="markerChange" />
                </el-form-item>

                <template v-if="showMore">
                    <el-form-item label="主图">
                        <image-picker v-model="currentItem.cover" width="200" height="150" />
                    </el-form-item>

                    <el-form-item label="参考均价">
                        <el-input maxlength="20" style="width: 200px" v-model="currentItem.price"></el-input>
                    </el-form-item>
                    <el-form-item label="开发商">
                        <el-input maxlength="50" style="width: 200px" v-model="currentItem.develop_company"></el-input>
                    </el-form-item>
                    <el-form-item label="物业公司">
                        <el-input maxlength="50" style="width: 200px" v-model="currentItem.property_company"></el-input>
                    </el-form-item>
                    <el-form-item label="物业费">
                        <el-input style="width: 200px" v-model="currentItem.property_fee"></el-input>
                    </el-form-item>
                </template>

                <el-form-item label="展开更多">
                    <el-switch v-model="showMore"></el-switch>
                </el-form-item>

                <div style="display: flex; justify-content: center">
                    <el-button block v-loading="loading" type="default" @click="closeHandle">取消</el-button>
                    <el-button block v-loading="loading" type="primary" @click="submitHandle">{{
                        submitBtnText
                    }}</el-button>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.inline {
    display: flex;
    justify-content: space-between;
}

.icon-uploader .el-upload,
.icon-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 355px;
    height: 150px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.icon-uploader img {
    width: 355px;
    height: 150px;
}

.icon-uploader .el-upload:hover {
    border-color: #409eff;
}

.app-container {
    .myheader {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px 0px;

        .part-right {
            display: flex;
            justify-content: flex-end;
            align-items: center;

            .block {
                margin-left: 10px;
            }
        }

        .part-left {
            display: flex;
            justify-content: flex-start;
            align-items: center;

            .block {
                margin-right: 10px;
                display: flex;
                align-items: center;
            }
        }

        .el-input {
            with: 250px;
            border-radius: 100%;
        }
    }
}
</style>

<script>
import {
    getSubDistrictList,
    updateSubDistrict,
    createSubDistrict,
    deleteSubDistrict,
} from "@/api/sub-district";
import ImagePicker from "@/components/ImagePicker";
import MapMarker from "@/components/MapMarker";
import { getToken } from "@/utils/auth";
import CityDistrictSelector from "@/components/CityDistrictSelector";
import CitySelector from "@/components/CitySelector.vue";
import DistrictSelector from "@/components/DistrictSelector";
import PoiSearch from "@/components/PoiSearch";
import { searchPoi } from "@/api/poi";

export default {
    name: "subdistricts",
    components: {
        ImagePicker,
        MapMarker,
        CityDistrictSelector,
        PoiSearch,
        CitySelector,
        DistrictSelector,
    },
    data () {
        return {
            kw: "",
            showForm: false,
            showMore: false,
            total: 0,
            per_page: 20,
            page: 1,
            items: [],
            cityId: null,
            districtId: null,
            loading: false,
            currentItem: { id: null, public: true, cover: "", content: "" },
        };
    },
    props: {},

    watch: {
        cityId: function () {
            this.page = 1
            this.loadData();
        },

        districtId: function () {
            this.page = 1
            this.loadData();
        },

        per_page: function () {
            this.page = 1
            this.loadData();
        },

        showForm: function () {
            this.loading = true;
            this.loadData();
        },
    },

    computed: {
        cityName () {
            return "";
        },

        districtName () {
            return "";
        },

        submitBtnText () {
            return this.currentItem.id ? "保存修改" : "创建";
        },
    },

    mounted: function () {
        this.loadData();
    },

    methods: {
        poiSelectHandle: function (poi) {
            console.log("poi select: ", poi);
            var item = this.currentItem;
            item.street = poi.address;
            item.name = poi.title;
            item.longitude = poi.location.lng.toString();
            item.latitude = poi.location.lat.toString();
            this.currentItem = item;
        },
        markerChange: function (marker) {
            if (!marker) {
                return false;
            }

            var item = this.currentItem;
            item.latitude = marker.lat;
            item.longitude = marker.lng;
            this.currentItem = item;
        },

        formtDateTimeValue: function (e) {
            if (typeof e === "object") {
                var v = e.toLocaleDateString();
                var y = e.getFullYear();
                var m = e.getMonth() + 1;
                var d = e.getDate();
                var date = y + "-" + m + "-" + d;
                var h = e.getHours();
                var m = e.getMinutes();
                var time = h + ":" + m;
                return date + " " + time;
            }
        },

        startsAtChange: function (e) {
            var value = this.formtDateTimeValue(e);
            var item = this.currentItem;
            item["starts_at"] = value;
            this.currentItem = item;
        },

        endsAtChange: function (e) {
            var value = this.formtDateTimeValue(e);
            var item = this.currentItem;
            item["ends_at"] = value;
            this.currentItem = item;
        },

        updateCurrentPage: function (page) {
            this.page = page;
            this.loadData()
        },

        updatePageSize: function (size) {
            this.per_page = size || 10;
        },

        closeHandle: function () {
            this.currentItem = {};
            this.showForm = false;
        },

        newFormHandle: function () {
            this.currentItem = {};
            this.showForm = true;
            this.loading = false;
        },
        editHandle: function (item) {
            this.showForm = true;
            this.currentItem = item;
        },

        doSearch: function () {
            // 搜索
            this.loading = true;
            this.page = 1;
            this.loadData();
        },

        clearKw: function () {
            this.kw = "";
            this.page = 1;
            this.loadData();
        },

        removeCover: function () {
            this.currentItem.cover = "";
        },

        itemSelect: function (item) {
            this.currentItem = item;
        },

        deleteHandle: function (itemId) {
            var _this = this;
            this.$confirm("确定要删除这个小区吗?", {
                confirmButtonText: "确定删除",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                deleteSubDistrict(itemId).then((resp) => {
                    _this.currentItem = {};
                    _this.loadData();
                });
            });
        },

        validate: function (data) {
            if (!data.district_id) {
                this.$message.error("请选择区域");
                return false;
            }

            if (!data.name || data.name.length <= 3) {
                this.$message.error("名称不能少于3个字");
                return false;
            }

            if (!data.street) {
                this.$message.error("请填写地址");
                return false;
            }

            if (!data.latitude || !data.longitude) {
                this.$message.error("请选择地图定位点");
                return false;
            }

            return true;
        },

        submitHandle: function () {
            var data = this.currentItem;
            var isok = this.validate(data);
            if (!isok) {
                return false;
            }

            this.loading = true;

            if (!data.id) {
                createSubDistrict(data).then((resp) => {
                    this.loading = false;
                    if (resp.status == 0) {
                        this.loadData();
                        this.$message.success("保存成功");
                    }
                });
                return;
            }

            updateSubDistrict(data).then((resp) => {
                this.loading = false;
                if (resp.status == 0) {
                    this.loadData();
                    this.$message.success("保存成功");
                }
            });
        },

        loadData: function () {
            this.loading = true;
            this.showMore = false;
            var query = {
                page: this.page,
                per_page: this.per_page,
                city_id: this.cityId || "",
                district_id: this.districtId || "",
                kw: this.kw,
            };
            console.log("query is", query);
            getSubDistrictList(query).then((resp) => {
                this.items = resp.data.result;
                this.total = resp.data.page.total_items;
                this.loading = false;
            });
        },
    },
};
</script>
